import inquirer from 'inquirer';
import chalk from 'chalk';
import { Logger } from '../utils/logger.js';
import { connectionMenu } from './connectionMenu.js';
import { configMenu } from './configMenu.js';

export async function mainMenu(sftpClient, configManager) {
  let shouldExit = false;

  while (!shouldExit) {
    Logger.separator();

    const { action } = await inquirer.prompt([
      {
        type: 'list',
        name: 'action',
        message: '请选择操作',
        choices: [
          {
            name: '🔌 连接到服务器',
            value: 'connect',
          },
          {
            name: '⚙️  配置管理',
            value: 'config',
          },
          {
            name: '📊 连接状态',
            value: 'status',
          },
          new inquirer.Separator(),
          {
            name: '❌ 退出',
            value: 'exit',
          },
        ],
      },
    ]);

    try {
      switch (action) {
        case 'connect':
          await connectionMenu(sftpClient, configManager);
          break;
        case 'config':
          await configMenu(configManager);
          break;
        case 'status':
          displayStatus(sftpClient);
          break;
        case 'exit':
          await sftpClient.disconnect();
          Logger.info('感谢使用，再见！');
          shouldExit = true;
          break;
      }
    } catch (error) {
      Logger.error(error.message);
    }
  }
}

function displayStatus(sftpClient) {
  Logger.separator();
  console.log(
    chalk.cyan('SFTP 连接状态:'),
    sftpClient.isConnected ? chalk.green('✓ 已连接') : chalk.red('✗ 未连接')
  );

  if (sftpClient.isConnected && sftpClient.currentConfig) {
    const config = sftpClient.currentConfig;
    console.log(chalk.cyan('服务器信息:'));
    console.log(`  - 主机: ${config.host}:${config.port}`);
    console.log(`  - 用户: ${config.username}`);
    console.log(`  - 认证: ${config.authType === 'password' ? '密码' : '私钥'}`);
  }
  Logger.separator();
}
